# pip install psutil
import psutil
import subprocess
from time import sleep
# This code was written by HuangStudio

# settings
# ====================================================
# 微信进程的完整名称 一般不需要改动
wechat_process_name = "WeChat.exe"
# 微信可执行文件的完整绝对路径 此处为默认路径 请按需更改
wechat_install_path = "C:\Program Files\Tencent\WeChat\WeChat.exe"
# ====================================================

def check_run(process_name):
    # 获取正在运行的进程
    pl = psutil.pids()
    # 遍历结果
    for pid in pl:
        if psutil.Process(pid).name() == process_name:
            # 查找到进程 返回pid
            return pid

def keep_wechat_running():
    while True:
        # 10s判断一次微信进程是否存在
        sleep(10)
        if isinstance(check_run(wechat_process_name), int):
            # 微信进程存在
            print("tmp -> WeChat is running now!")
            # 继续
            continue
        else:
            # 微信进程丢失
            print("tmp -> Wechat is stoping!")
            print("tmp -> wait for restart")
            # 启动微信进程
            subprocess.Popen(wechat_install_path)
            continue


# 运行函数
keep_wechat_running()
